import { TOKEN_TIME, TOKEN_TIME_VALUE,TOKEN } from './constant'
import { ElMessage, ElMessageBox,ElNotification } from "element-plus";
// 登录时设置时间
export const setTokenTime = () => {
  localStorage.setItem(TOKEN_TIME, Date.now())
}

// 获取
export const getTokenTime = () => {
  return localStorage.getItem(TOKEN_TIME)
}

// 获取token
export const getToken = () => {
  return localStorage.getItem(TOKEN)
}

/**
 * 获取用户信息
 * @returns {string|[{trigger: string, message: string, required: boolean}]|*}
 */
export const getUser = () => {
  return  JSON.parse(localStorage.getItem('userData'));
}

/**
 * 获取用户ID
 * @returns {string|[{trigger: string, message: string, required: boolean}]|*}
 */
export const getUserId = () => {
  let user = JSON.parse(localStorage.getItem('userData'))
  return user.userId;
}

/**
 * 获取用户名称
 * @returns {string|[{trigger: string, message: string, required: boolean}]|*}
 */
export const getRealName = () => {
  let user = JSON.parse(localStorage.getItem('userData'))
  return user.realName;
}
/**
 * 获取角色ID
 * @returns {[{trigger: string, message: string, required: boolean}]}
 */
export const getRoleId = () => {
  let user = JSON.parse(localStorage.getItem('userData'))
  return user.roleId;
}
/**获取角色别名，或名称*/
export const getRoleDesc = () => {
  let user = JSON.parse(localStorage.getItem('userData'))
  return user.roleDesc;
}
//表格中没数据时显示--
export const formatterTableCell = (row, column, cellValue, index) => {
    return ['', null].includes(cellValue) ? '--' : cellValue
  }
// 是否已经过期
export const diffTokenTime = () => {
  const currentTime = Date.now()
  const tokenTime = getTokenTime()
  return currentTime - tokenTime > TOKEN_TIME_VALUE
}
//修改时间戳为年月日
export const getymd = (dateStr) => {
  let d = new Date(dateStr),
  month = '' + (d.getMonth() + 1),
  day = '' + d.getDate(),
  year = d.getFullYear();

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

 return [year, month, day].join('-');
}
//修改时间戳为时分秒
export const getymdhms = (dateStr)=>{
  let d = new Date(dateStr),
  month = '' + (d.getMonth() + 1),
  day = '' + d.getDate(),
  year = d.getFullYear(),
  hour = ''+d.getHours(),
  minute = '' + d.getMinutes(),
  second = ''+d.getSeconds()
  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;
  if (hour.length < 2) hour = '0' + hour;
  if (minute.length < 2) minute = '0' + minute;
  if (second.length < 2) second = '0' + second;
  return [year, month, day].join('-') + ' '+[hour,minute,second].join(':');
}
//修改时间戳为时分秒
export const gethms = (dateStr)=>{
    let d = new Date(dateStr),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear(),
    hour = ''+d.getHours(),
    minute = '' + d.getMinutes(),
    second = ''+d.getSeconds()
    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;
    if (hour.length < 2) hour = '0' + hour;
    if (minute.length < 2) minute = '0' + minute;
    if (second.length < 2) second = '0' + second;
    return [hour,minute,second].join(':');
  }
  //修改时分秒为时间戳
  export const getDate = (dateStr)=>{
    return [new Date(),new Date()];
  }  
//判断是否为当天时间
export const isToday =(date)=> {
    return new Date().toString().substr(0, 15) === date.toString().substr(0, 15);
  }
export const dispatchEventStorage = () => {
  const signSetItem = localStorage.setItem
  localStorage.setItem = function(key, val) {
      let setEvent = new Event('setItemEvent')
      setEvent.key = key
      setEvent.newValue = val
      window.dispatchEvent(setEvent)
      signSetItem.apply(this, arguments)
  }
}
export const readFile = (file) => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsBinaryString(file.raw);
    reader.onload = (ev) => {
      resolve(ev.target.result)
    }
  })
}
/**
 * 
 * @param {*} objList : 下拉数据
 * @param {*} value 选中的value
 * @param {*} key value对应的key
 * @param {*} keylabel label对应的key
 */
export const getKey = (objList, value,key,keylabel) => {
  objList.forEach(item => {
    if(item[key] == value){
       return item[keylabel]
    }
  });
}

//图片解决下载跨域
export function getImage2Blob (url) {
  return new Promise((resolve, reject) => {
      var xhr = new XMLHttpRequest();
      xhr.open('get', url, true);
      xhr.responseType = 'blob';
      xhr.onload = function () {
          if (this.status == 200) {
              const blob = URL.createObjectURL(this.response);
              resolve(blob);
          } else {
              reject(false);
          }
      };
      xhr.send();
  });
}
// 校验图片格式
export const beforeAvatarUpload = (file)=>{
  const testmsg = /^image\/(png|jpg|jpeg)$/.test(file.type)
  if (!testmsg) {
    ElMessage.error('上传格式不正确,只支持JPG/PNG!')
    return false
  } else if (file.size && file.size / 1024/1024 > 10) {
    ElMessage.error('上传大小不正确,大小不超过10Mb!')
    return false
  }
}
//上传超出图片限制
export const handleExceedCover = (res, file)=>{
  ElMessage.error({
                  message: `上传图片数量超出限制！`,
                  type: "error",
              });
}
export const filebeforeUpload = (file) =>{
  // ".pdf,.docx,.doc,.xls,.xlsx,.ppt,.mp4,.pptx"
      const typeExtensions= ['pdf', 'docx','xlsx','mp4','pptx']; // 可以自定义需要支持的音频格式
      const fileExtension = file.name.split('.').pop().toLowerCase(); // 根据文件名获取文件扩展名并转换为小写字母形式
      if (typeExtensions.includes(fileExtension) == false) {
          ElMessage({
              type: 'error',
              message: '只能上传PDF，Word，Excel，PPT和MP4格式的文件',
          })
      }
      return typeExtensions.includes(fileExtension);
    }

// 禁止选择当天之前的日期
export const disabledDate = (time) =>{
    return time.getTime() < Date.now() - 8.64e7;
}

export const getNowDate = () => {
	let t = new Date()
	let y = t.getFullYear()
	let m = t.getMonth() + 1
	m = m < 10 ? '0' + m : m
	let d = t.getDate()
	d = d < 10 ? '0' + d : d
	
	let h = t.getHours()
	let mm = t.getMinutes()
	mm = mm < 10 ? '0' + mm : mm
	let s = t.getSeconds()
	s = s < 10 ? '0' + s : s
	return y + '-' + m + '-' + d + ' ' + h + ':' + mm + ':' + s
};